package com.kanshu.ksgb.fastread.doudou.common.util;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;

import com.kanshu.ksgb.fastread.doudou.base.baseui.BaseActivity;

import java.util.Stack;

/**
 * Created by wcy on 2017/4/13.
 */

public class ActivityMgr {

    private Stack<Activity> activityStack;
    private volatile static ActivityMgr instance;

    private ActivityMgr() {

    }
    /**
     * 单一实例
     */
    public static ActivityMgr getInstance() {
        if (instance == null) {
            synchronized (ActivityMgr.class){
                if(instance==null){
                    instance = new ActivityMgr();
                    instance.activityStack = new Stack();
                }
            }

        }
        return instance;
    }

    /**
     * 添加Activity到堆栈
     */
    public void addActivity(Activity activity) {
        if (activityStack == null) {
            activityStack = new Stack<Activity>();
        }
        activityStack.add(activity);
    }

    /**
     * 获取当前Activity（堆栈中最后一个压入的）
     */
    public Activity currentActivity() {
        try {
            Activity activity = activityStack.lastElement();
            return activity;
        } catch (Exception e) {
//            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取当前Activity的前一个Activity
     */
    public Activity preActivity() {
        int index = activityStack.size() - 2;
        if (index < 0) {
            return null;
        }
        Activity activity = activityStack.get(index);
        return activity;
    }

    /**
     * 结束当前Activity（堆栈中最后一个压入的）
     */
    public void finishOneActivity() {
        Activity activity = activityStack.lastElement();
        finishOneActivity(activity);
    }

    /**
     * 结束指定的Activity
     */
    public void finishOneActivity(Activity activity) {
        if (activity != null) {
            activityStack.remove(activity);
            activity.finish();
            activity = null;
        }
    }

    /**
     * 移除指定的Activity
     */
    public void removeActivity(Activity activity) {
        if (activity != null) {
            activityStack.remove(activity);
            activity = null;
        }
    }

    /**
     * 结束指定类名的Activity
     */
    public void finishOneActivity(Class<?> cls) {
        try {
            for (Activity activity : activityStack) {
                if (activity.getClass().equals(cls)) {
                    activity.finish();
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public boolean existActivity(Class<?> cls) {
        for (Activity activity : activityStack) {
            if (activity.getClass().equals(cls)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 结束所有Activity
     */
    public void finishAllActivity() {
        for (int i = 0, size = activityStack.size(); i < size; i++) {
            if (null != activityStack.get(i)) {
                activityStack.get(i).finish();
            }
        }
        activityStack.clear();
    }

    public void finishAllExcept(Class<?> cls) {
        for (int i = 0, size = activityStack.size(); i < size; i++) {
            Activity activity = activityStack.get(i);
            if (null != activity && !activity.getClass().equals(cls)) {
                activity.finish();
            }
        }
    }

    public void returnToFirstOrFinish(Class<?> cls, String bookId) {
        int num = 0;
        int firstPos = 0;
        int endPos = 0;
        boolean first = false;
        for (int i = 0, size = activityStack.size(); i < size; i++) {
            Activity activity = activityStack.get(i);
            if (null != activity && activity.getClass().equals(cls)) {
                if (!first) {
                    firstPos = i;
                    first = true;
                }
                endPos = i;
                num++;
            }
        }
        if (num > 1) {
            for (int i = endPos ; i > firstPos; i--) {
                Activity activity = activityStack.get(i);
                if (null != activity ) {
                    activity.finish();
                }
            }
        } else {
            finishOneActivity(cls);
        }
        Activity activity = activityStack.get(firstPos);
        Object tag = activity.getWindow().getDecorView().getTag();
        if(tag!= null && TextUtils.equals(bookId, tag.toString())){
            activity.finish();
        }
    }

    public int getActivityCount(Class<?> cls){
        int num = 0;
        for (int i = 0, size = activityStack.size(); i < size; i++) {
            Activity activity = activityStack.get(i);
            if (null != activity && activity.getClass().equals(cls)) {
                num++;
            }
        }
        return num;
    }

    /**
     * 返回到指定的activity
     *
     * @param cls
     */
    public void returnToActivity(Class<?> cls) {
        while (activityStack.size() != 0)
            if (activityStack.peek().getClass() == cls) {
                break;
            } else {
                finishOneActivity(activityStack.peek());
            }
    }


    /**
     * 是否已经打开指定的activity
     * @param cls
     * @return
     */
    public boolean isOpenActivity(Class<?> cls) {
        if (activityStack!=null){
            for (int i = 0, size = activityStack.size(); i < size; i++) {
                if (cls == activityStack.peek().getClass()) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 退出应用程序
     *
     * @param context      上下文
     * @param isBackground 是否开开启后台运行
     */
    public void AppExit(Context context, Boolean isBackground) {
        try {
            finishAllActivity();
            ActivityManager activityMgr = (ActivityManager) context
                    .getSystemService(Context.ACTIVITY_SERVICE);
            activityMgr.restartPackage(context.getPackageName());
        } catch (Exception e) {

        } finally {
            // 注意，如果您有后台程序运行，请不要支持此句子
            if (!isBackground) {
                System.exit(0);
            }
        }
    }

    public int getActivityCount() {
        if (activityStack != null) {
            return activityStack.size();
        }
        return 0;
    }

    /**
     * 通过tag标识页面 并查找到页面
     * @param tag
     * @return
     */
    public boolean existPageByTag(String tag) {
        for (Activity activity : activityStack) {
            Window window = activity.getWindow();
            if (window == null) {
                continue;
            }
            View decorView = window.getDecorView();
            if (decorView == null) {
                continue;
            }
            Object tag1 = decorView.getTag();
            if (tag1 == null) {
                continue;
            }
            if (TextUtils.equals(tag, tag1.toString())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取页面的tag
     * @param activity
     * @return
     */
    public String getActivityTag(Activity activity) {
        if (activity != null) {
            Window window = activity.getWindow();
            if (window == null) {
                return "";
            }
            View decorView = window.getDecorView();
            if (decorView == null) {
                return "";
            }
            if (decorView.getTag() == null) {
                return "";
            }
            return decorView.getTag().toString();
        }
        return "";
    }

    /**
     * 获取栈顶的activity
     * @return
     */
    public Activity peek() {
        return activityStack.lastElement();
    }
}
